package com.joysuch.wwyt.datadump.biz.processor;

import cn.zlg.common.datadump.annotation.DataDumpEntity;
import cn.zlg.common.datadump.processor.BaseImportEntityProcessor;
import com.joysuch.wwyt.bp.entity.contractor.BpContractorStaff;
import com.joysuch.wwyt.bp.entity.contractor.dsl.QBpContractorStaff;
import com.joysuch.wwyt.bp.entity.investigate.BpInvestigateStore;
import com.joysuch.wwyt.bp.entity.investigate.BpInvestigateStoreDetail;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.bp.repository.BpInvestigateStoreRepository;
import com.joysuch.wwyt.core.entity.dsl.QBaseUser;
import com.joysuch.wwyt.datadump.biz.model.BpContractorStaffDumpBean;
import com.joysuch.wwyt.datadump.biz.model.BpInvestigateStoreDetailDumpBean;
import com.mysema.commons.lang.Assert;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.SimpleExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BpInvestigateStoreDetailImportProcessor extends BaseImportEntityProcessor<BpInvestigateStoreDetailDumpBean, BpInvestigateStoreDetail> {

    @Autowired
    private BpInvestigateStoreRepository storeRepository;

    /**
     * 导入时，依次检查上上级、上级、当前级标准库是否存在，不存在依次创建
     * @param origin
     * @param entity
     * @param annotation
     * @param override 覆盖已有记录
     * @return
     */
    @Override
    public BpInvestigateStoreDetail processBeforeSave(BpInvestigateStoreDetailDumpBean origin, BpInvestigateStoreDetail entity, DataDumpEntity annotation) {
        BpInvestigateStore grandparent = createStoreIfNotExist(origin.getGrandfatherStoreName(), 0L, false);
        BpInvestigateStore parent = createStoreIfNotExist(origin.getParentStoreName(), grandparent.getId(), false);
        BpInvestigateStore son = createStoreIfNotExist(origin.getStoreName(), parent.getId(), true);
        entity.setStoreId(son.getId());
        entity.setStoreName(son.getCheckTypeName());
        return entity;
    }

    private BpInvestigateStore createStoreIfNotExist(String content, Long parentId, boolean topOrNot) {
        BpInvestigateStore store = storeRepository.findFirstByCheckTypeNameAndParentId(content, parentId);
        if(store == null) {
            store = new BpInvestigateStore(content, parentId, topOrNot);
            store = storeRepository.save(store);
        }
       return store;
    }


}
